package com.ldc.common.utils;

import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 功能描述
 *
 * @author liudi
 * @since 2023/7/29
 */
public class FileUtils {

    public static String getSaveRootPath() {
        return new File("").getAbsolutePath();
    }

    public static String getSaveCachePath() {
        String path = getSaveRootPath() + File.separator + "cache";
        createDir(path);
        return path;
    }

    public static String getSaveFilePath() {
        String path = getSaveCachePath() + File.separator + "files";
        createDir(path);
        return path;
    }

    public static String getSaveImagesPath() {
        String path = getSaveCachePath() + File.separator + "images";
        return createDir(path);
    }


    public static String createDir(String dirPath) {
        if (StringUtils.isEmpty(dirPath)) {
            return null;
        }
        File dir = new File(dirPath);
        boolean success = true;
        if (!dir.exists()) {
            success = dir.mkdirs();
        }
        return success ? dirPath : null;
    }

    public static File createFile(String filePath) throws IOException {
        if (StringUtils.isEmpty(filePath)) {
            return null;
        }
        File newFile = new File(filePath);
        boolean success = true;
        if (!newFile.exists()) {
            success = newFile.createNewFile();
        }
        return success ? newFile : null;
    }

    public static byte[] getFileBytes(String filePath) {
        File file = new File(filePath);
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            byte[] b = new byte[1024];
            int n = 0;
            while ((n = fis.read()) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            byte[] data = bos.toByteArray();
            bos.close();
            return data;
        } catch (IOException error) {
            error.printStackTrace();
        }
        return null;
    }

    /**
     * 将Byte数组转换成文件
     *
     * @param bytes
     */
    public static void saveFile(byte[] bytes, String filePath) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            final File file = createFile(filePath);
            if (null == file) return;
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            // 报错
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    // io 异常
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    // io异常
                }
            }
        }
    }


    public static String getNewFileName(MultipartFile file) {
        if (null == file) {
            return null;
        }
        long dateTime = DateTimeUtils.getTime();
        String prefix = getFilePrefixName(file.getOriginalFilename());
        String suffix = getFileExtension(file.getOriginalFilename());
        return String.format("%s_%s%s", prefix, dateTime, suffix);
    }

    public static String getFileExtension(String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            return "";
        }
        int index = filePath.lastIndexOf(".");
        return filePath.substring(index);
    }

    public static String getFilePrefixName(String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            return "";
        }
        int index = filePath.lastIndexOf(".");
        return filePath.substring(0, index);
    }

    public static long getFileSize(File file) {
        return file == null ? 0 : file.length();
    }

    public static void downloadFile(HttpServletResponse response, String filePath) {
        try {
            if (StringUtils.isEmpty(filePath)) {
                return;
            }
            InputStream inputStream = new FileInputStream(filePath);// 文件的存放路径
            response.reset();
            response.setContentType("application/octet-stream");
            String filename = new File(filePath).getName();
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
            while ((len = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
            inputStream.close();
        } catch (Exception error) {
            error.printStackTrace();
        }
    }
}
